#! /bin/sh

set -e

TAG="jasonish/suricata-elk"

VOLUMES="-v $(pwd)/data:/data"
VOLUMES="${VOLUMES} -v $(pwd)/data/var/log/suricata:/var/log/suricata"

use_privileged() {
    if [ "$(getenforce 2>/dev/null)" = "Enforcing" ]; then
	printf -- "--privileged"
    fi
}

enter() {
    if [ ! -e cid ]; then
	echo "error: container does not appear to be running."
	exit 1
    fi
    docker exec -it $(cat cid) /bin/bash
}

start() {

    if [ -e cid ]; then
	if ! docker ps --no-trunc -q | grep -q $(cat cid); then
	    echo "Removing stale cid."
	    rm -f cid
	else
	    echo "error: container appears to be running."
	    exit 1
	fi
    fi

    test -e data || mkdir data
    docker run \
	$(use_privileged) --rm --cidfile=cid --net=host -i -t ${PORTS} \
	${VOLUMES} \
	-e HOST_UID=$(id -u) \
	${TAG} "$@"
    rm -f cid
}

usage() {
    echo "Usage: launcher <command> [args]"
    echo
    echo "Commands:"
    echo
    echo "  start [-i interface]    Start the container"
    echo "  enter                   Get a shell in the running container"
    echo "  bash                    Start the container with a shell"
    echo "  pull                    Update the image"
    echo "  build                   (Re)build the image"
    echo
}

case "$1" in

    start)
	shift
	start "$@"
	;;

    bash)
	docker run --rm --entrypoint=/bin/bash \
	    --net=host -i -t ${VOLUMES} ${TAG}
	;;

    build)
	docker build --rm -t ${TAG} image
	;;

    enter)
	enter
	;;

    supervisorctl)
	enter supervisorctl
	;;

    pull)
	docker pull ${TAG}
	;;

    *)
	usage
	;;

esac
